package com.jeecms.wicool.dao.product.impl;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.common.hibernate3.Finder;
import com.jeecms.common.hibernate3.HibernateBaseDao;
import com.jeecms.common.page.Pagination;
import com.jeecms.wicool.dao.product.ProductCateDao;
import com.jeecms.wicool.entity.product.ProductCate;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ProductCateDaoImpl extends HibernateBaseDao<ProductCate, Integer>
        implements ProductCateDao {

    @Override
    protected Class<ProductCate> getEntityClass() {
        return ProductCate.class;
    }

    @Override
    public Pagination getPage(String cateName, Integer cateLevel, int pageNo, int pageSize, CmsUser user) {
        Finder f = Finder.create("select bean from ProductCate bean where 1=1 ");
        if (!StringUtils.isBlank(cateName)) {
            f.append(" and bean.cateName like :cateName");
            f.setParam("cateName", "%" + cateName + "%");
        }
        if (cateLevel != null) {
            f.append(" and bean.cateLevel = :cateLevel");
            f.setParam("cateLevel", cateLevel);
        }
        if (user.getShopId() != null) {
            f.append(" and bean.shop.id = :shopId");
            f.setParam("shopId", user.getShopId());
        }
        f.append(" order by bean.id desc");
        return find(f, pageNo, pageSize);
    }

    @Override
    public ProductCate findById(Integer id) {
        ProductCate entity = get(id);
        return entity;
    }

    @Override
    public ProductCate save(ProductCate bean) {
        getSession().save(bean);
        return bean;
    }

    @Override
    public List<ProductCate> getListByCateLevel(Integer level, CmsUser user) {
        Finder f = Finder.create("select bean from ProductCate bean where 1=1 ");
        if (level != null) {
            f.append(" and bean.cateLevel = :level");
            f.setParam("level", level);
        }
        if (user.getShopId() != null) {
            f.append(" and bean.shop.id = :shopId");
            f.setParam("shopId", user.getShopId());
        }
        f.append(" order by bean.id desc");
        return find(f);
    }

    @Override
    public ProductCate deleteById(Integer id) {
        ProductCate entity = super.get(id);
        if (entity != null) {
            getSession().delete(entity);
        }
        return entity;
    }

    @Override
    public List<ProductCate> getAll() {
        Finder f = Finder.create("select bean from ProductCate bean where 1=1 order by bean.updateTime");
        return find(f);
    }
}